<?php include('../fns_all.php'); ?>
<?php require_once('../user.php'); ?>

<?php
/* Program: Login.php
* Desc: Main application script for the User Login
* application. It provides two options: (1) login
* using an existing User Name and (2) register
* a new user name. User Names and passwords are
* stored in a MySQL database.
*/
session_start();

if(( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) || ( $_SESSION['security_code'] == $_POST['security_code2'] && !empty($_SESSION['security_code'] ) )){
	unset($_SESSION['security_code']);
	unset($_SESSION['security_code2']);
}else {
	$message_1="Sorry, you have provided an invalid security code";
	//include('../fns_all.php');//because on top is already included
	include('../views/layouts/_header.php');
	include('../views/layouts/_left.php');
	extract($_POST);
	include("fields_login.inc");
	include("double_form.inc");
	include('../views/layouts/_footer.php');

	exit();
}


function includeRegisterForm(){
	include('../views/layouts/_header.php');
	include('../views/layouts/_left.php');
	include("fields_login.inc");
	include("double_form.inc");
	include('../views/layouts/_footer.php');
}

//function del_article_img($id){
//	$result = get_article_by_id($id);
//	$row = mysqli_fetch_assoc( $result );
//	unlink("../images/articles/thumbnails/".$row['img_path']);
//	unlink("../images/articles/".$row['img_path']);
//}

function add_img_to_user($id){

	//logToFile("log.txt", '>>> in add_img_to_article()');
	unset($imagename);

    if(!isset($_FILES) && isset($HTTP_POST_FILES))
    	$_FILES = $HTTP_POST_FILES;

    //print_r($_FILES);
    if(!isset($_FILES['img_file'])){
    	$error["img_file"] = "An image was not found.";
    	echo $error;
    	return;
    }

    $imagename = basename($_FILES['img_file']['name']);

    if(empty($error) && isset($imagename) && $imagename != null && $imagename != "")
    {
//    	if(isset($cxn)){
//    		del_article_img($id);
//    	}

    	$newimage = "../images/" . $imagename;
    	$result = @move_uploaded_file($_FILES['img_file']['tmp_name'], $newimage);
    	if(empty($result)){
    		$error["result"] = "There was an error moving the uploaded file.";
    	}
    	resampimagejpg(450, 750, $newimage, "../images/users/".$imagename, 40);
    	resampimagejpg(150, 250, $newimage, "../images/users/thumbnails/".$imagename, 20);
    	unlink($newimage);
    }else{
    	echo $error;

    }

	//logToFile("log.txt", ">>> image saved");
    return $imagename;
}



$table_name = "users";

$cxn = db_connect();


if(isset($_POST['page'])){
	$next_program = '/'.$_POST['page'];
}else{
	$next_program = "/";
}
switch (@$_POST['Button'])
{

	case "Login":

	$sql = "SELECT user_name FROM $table_name WHERE user_name='$_POST[fusername]'";
	$result = mysqli_query($cxn,$sql) or die("Couldn't execute query 1");
	$num = mysqli_num_rows($result);
	if($num == 1)
	{
		$sql = "SELECT * FROM $table_name
		WHERE user_name='$_POST[fusername]'
		AND password=md5('$_POST[fpassword]')";
		$result2 = mysqli_query($cxn,$sql) or die("Couldn't execute query 2.");
		$row = mysqli_fetch_assoc($result2);
		if($row)
		{
			$_SESSION['auth']="yes";
			$_SESSION['logname'] = $_POST['fusername'];

			$user = new user($row['id'], $row['user_name'], $row['first_name'], $row['last_name'], $row['email'], $row['city'], $row['country'], $row['create_date'], $row['img_path']);
			$_SESSION['user'] = $user;

			header("Location: $next_program");
		}
		else
		{
			$message_1="The Login Name, '$_POST[fusername]'
			exists, but you have not entered the
			correct password! Please try again.<br>";
			extract($_POST);
			includeRegisterForm();
		}
	}
	elseif ($num == 0) // login name not found #47
	{
		$message_1 = "The User Name you entered does not
		exist! Please try again.<br>";
		includeRegisterForm();
	}
	break;


	case "Register":

	/* Check for blanks */
	foreach($_POST as $field => $value)
	{
		if ($field != "fax")
		{
			if ($value == "")
			{
				$blanks[] = $field;
			}
		}
	}

	if(isset($blanks))
	{
		$message_2 = "The following fields are blank.
		Please enter the required information: ";
		foreach($blanks as $value)
		{
			$message_2 .="$value, ";
		}
		extract($_POST);
		includeRegisterForm();
		exit();
	}

	/* validate data */
	foreach($_POST as $field => $value)
	{
		if(!empty($value))
		{
			if(eregi("name",$field) and !eregi("user",$field) and !eregi("log",$field))
			{
				if (!ereg("^[A-Za-z' -]{1,50}$",$value))
				{
					$errors[] = "$value is not a valid name.";
				}
			}
//			if(eregi("street",$field)or eregi("addr",$field) or
//			eregi("city",$field))
//			{
//				if(!ereg("^[A-Za-z0-9.,' -]{1,50}$",$value))
//				{
//					$errors[] = "$value is not a valid address
//					or city.";
//				}
//			}
//			if(eregi("state",$field))
//			{
//				if(!ereg("[A-Za-z]",$value))
//				{
//					$errors[] = "$value is not a valid state.";
//				}
//			}
			if(eregi("email",$field))
			{
				if(!ereg("^.+@.+\\..+$",$value))
				{
					$errors[] = "$value is not a valid email address.";
				}
			}
//			if(eregi("zip",$field))
//			{
//				#if(!ereg("^[0-9]{5,5}(\-[0-9]{4,4})?$",$value))
//				if(false)
//				{
//					$errors[] = "$value is not a valid zipcode.";
//				}
//			}
//			if(eregi("phone",$field) or eregi("fax",$field))
//			{
//				#if(!ereg("^[0-9)(xX -]{7,20}$",$value))
//				if(false)
//				{
//					$errors[] = "$value is not a valid phone number. ";
//				}
//			}
		}
	}

	foreach($_POST as $field => $value)
	{
		if($field != "Button" && $field != "security_code2")
		{
			//logToFile("log.txt", "field: $field, value: $value");
			//logToFile("log.txt", "in if for fields");
			if($field == "password"){
				//logToFile("log.txt", "in if for password");
				$password = strip_tags(trim($value));
			}else if($field == "repeat_password"){
				//logToFile("log.txt", "in if for repeat_password");
				$repeat_password = strip_tags(trim($value));
			}else if($field == "img_file"){
//				logToFile("log.txt", "in if for img_file");
//				$imagename = add_img_to_user(null);
//				logToFile("log.txt", $imagename);
			}else{
				$fields[]=$field;
				$value = strip_tags(trim($value));
				$values[]=addslashes($value);
				$$field = $value;
			}
		}
	}

	$imagename = add_img_to_user(null);
	logToFile("log.txt", $imagename);

	if($password != $repeat_password){
		$message_2 = "Please make sure the Password and Repeat Password fields contain the same.";
		includeRegisterForm();
		exit();
	}

	if(@is_array($errors))
	{
		$message_2 = "";
		foreach($errors as $value)
		{
			$message_2 .= $value." Please try again<br />";
		}
		includeRegisterForm();
		exit();
	}

	$user_name = $_POST['user_name'];
	/* check to see if user name already exists */

	$sql = "SELECT user_name FROM $table_name WHERE user_name='$user_name'";
	$result = mysqli_query($cxn,$sql) or die("Couldn't execute query.");
	$num = mysqli_num_rows($result);

	if ($num > 0){
		$message_2 = "$user_name already used. Select another User Name.";
		includeRegisterForm();
		exit();
	}else{
		$today = date("Y-m-d");
		$fields_str = implode(",",$fields);
		//print_r($values);
		$values_str = implode('","',$values);
		$fields_str .=",create_date";
		$values_str .='"'.",".'"'.$today;
		$fields_str .=",img_path";
		$values_str .='"'.",".'"'.$imagename;
		$fields_str .=",password";
		$values_str .= '"'.","."md5"."('".$password."')";
		$sql = "INSERT INTO $table_name ";
		$sql .= "(".$fields_str.")";
		$sql .= " VALUES ";
		$sql .= "(".'"'.$values_str.")";
		mysqli_query($cxn,$sql) or die(mysqli_error($cxn));
		$_SESSION['auth']="yes";
		$_SESSION['logname'] = $user_name;
//		$user = new user($row['user_name'], $row['first_name'], $row['last_name'], $row['email'], $row['city'], $row['country'], $row['create_date']);
//		$_SESSION['user'] = $user;
		/* send email to new user */
		$emess = "You have successfully registered. ";
		$emess .= "Your new user name and password are: ";
		$emess .= "\n\n\t$user_name\n\t";
		$emess .= "$password\n\n";
		$emess .= "We appreciate your interest. \n\n";
		$emess .= "If you have any questions or problems,";
		$emess .= " email admin@fmaniac.com";
		$subj = "Your new user registration";
		@mail( $email, $subj, $emess, "From: admin@fmaniac.com" );
		header("Location: $next_program");
	}
	break;

	default:
	includeRegisterForm();
}
?>